//
//  Status.m
//  TwitterPlane
//
//  Created by kazuyuki takahashi on 10/01/16.
//  Copyright 2010 by invisibledesigner.com. All rights reserved.
//

#import "Status.h"
#import "User.h"
#import "NSString+XML.h"

@implementation Status

@synthesize text = text_;
@synthesize user = user_;
@synthesize statusID = statusID_;
@synthesize updatedDate = updatedDate_;
@synthesize receivedDate = receivedDate_;
@synthesize retweeter = retweeter_;

+ (NSString*)statusIDWithDictionary:(NSDictionary *)dic
{
    return [dic objectForKey:@"id"];
}

+ (NSComparator)statusIDComparator
{
    NSComparator cmp = ^(id id1, id id2) {
        long long llid1 = [id1 longLongValue];
        long long llid2 = [id2 longLongValue];
        if (llid1 < llid2) {
            return (NSInteger)NSOrderedAscending;
        } else if (llid1 == llid2) {
            return (NSInteger)NSOrderedSame;
        } else {
            return (NSInteger)NSOrderedDescending;
        }
    };
    return [[cmp retain] autorelease];
}

- (id)initWithDictionary:(NSDictionary*)dic
{
    NSParameterAssert(dic != nil);
    
    //RTのとき
    if ([dic objectForKey:@"retweeted_status"]) {
        Status *s = [self initWithDictionary:[dic objectForKey:@"retweeted_status"]];
        if (s) {
            //タイムラインの並び調整のためにIDだけはretweetのものにさしかえ
            [s->statusID_ release];
            s->statusID_ = [[dic objectForKey:@"id"] retain];
            //RTしたひとのなまえ取得
            s->retweeter_ = [[[dic objectForKey:@"user"] objectForKey:@"screen_name"] retain];
        }
        return s;
    }
    
    self = [super init];
    if (self) {
        statusID_ = [[dic objectForKey:@"id"] retain];
        text_ = [[[dic objectForKey:@"text"] stringByUnescapingXMLSpecialChars] retain];
        
        NSInteger tz = [[NSTimeZone systemTimeZone] secondsFromGMT];
        updatedDate_ = [[[dic objectForKey:@"created_at"] dateByAddingTimeInterval:tz] retain];
        
        receivedDate_ = [[NSDate alloc] init];
        
        NSDictionary *userdic = [dic objectForKey:@"user"];
        if (userdic) {
            user_ = [[User userForDictionary:userdic] retain];
        }
        
        if (!(statusID_ && text_ && user_ && updatedDate_)) {
            NSAssert(NO, @"invalid parameters");
            [self release];
            self = nil;
        }
    }
    return self;
}

- (id)init 
{
    NSAssert(NO, @"invalid initializer");
    [self release];
    return self = nil;
}

- (void)dealloc
{
    [text_ release];
    [user_ release];
    [statusID_ release];
    [updatedDate_ release];
    [receivedDate_ release];
    [retweeter_ release];
    [super dealloc];
}

@end
